package selfLearn.theList.symbol;

/**
 * 描述:无序号表
 *
 * @Package: selfLearn.theList
 * @ClassName: symbol
 * @Author: 陈威
 * @CreateTime: 2022/2/16 14:17
 * @Description:
 */
public class SymbolTable<Key, Value> {
    //头节点
    private Node head;
    //节点数量
    private Integer n;

    private class Node {
        private Key key;
        private Value value;
        private Node next;

        public Node(Key key, Value value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    public SymbolTable() {
        this.head = new Node(null, null, null);
        this.n = 0;
    }

    //根据key获取对应节点的值
    public Value get(Key key) {
        Node tar = head;
        while (tar.next != null) {
            tar = tar.next;
            if (tar.key.equals(key)) {
                return tar.value;
            }
        }
        return null;
    }

    //插入节点
    public void put(Key key, Value value) {
        Node tar = head;
        //遍历符号表中是否已存在该key
        while (tar.next != null) {
            tar = tar.next;
            //如果参数key在节点中已存在，那么因为唯一的特性，那么将原来的value替换为现在的value
            if (tar.key.equals(key)) {
                tar.value = value;
                return;
            }
        }
        //节点中不存在key则进行添加操作
        Node node = new Node(key, value, null);
        Node oldNode = head.next;
        node.next = head.next;
        head.next = node;
        n++;
    }


    public void delete(Key key) {
        Node tar = head;
        while (tar.next != null) {
            if (tar.next.key.equals(key)) {
                tar.next = tar.next.next;
                n--;
                return;
            }
            tar = tar.next;
        }
    }
    //遍历符号表
    public void foreachTable(){
        if(head.next==null){
            return;
        }
        Node tar=head;
        while (tar.next!=null){
            tar=tar.next;
            System.out.println("key="+tar.key+",value="+tar.value);
        }
    }
}
